/***************************************************************************
 * 文件名：FileUtil
 * 功能：
 * 说明： 文件工具类
 * -------------------------------------------------------------------------
 * 创建时间：2025/6/19 9:11:02
 * 创建人：葛浩
 * 邮箱： 2094733071@qq.com
 * =========================================================================
 *
 * 修改人：   
 * 修改时间：   
 * 修改说明：   
 ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.AccessControl;
using System.Text.RegularExpressions;

namespace Util
{
	/// <summary>
	/// 文件帮助类
	/// </summary>
	public class FileHelperUtil
	{
		#region 当前用户的Laocal文件夹路径

		/// <summary>
		/// 获取当前用户的Laocal文件夹路径
		/// </summary>
		/// <returns></returns>
		public static string GetAppDataFolderPath()
		{
			return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
		}

		#endregion

		#region 正则匹配是否以某字符串开头（环境变量使用）

		/// <summary>
		/// 匹配以某字符串开头
		/// </summary>
		/// <param name="input"></param>
		/// <param name="fixedBegin"></param>
		/// <returns></returns>
		public static bool IsMatchFixedBeginning(string input, string fixedBegin)
		{
			try
			{
				if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(fixedBegin))
				{
					return false;
				}

				return Regex.IsMatch(input, string.Format("^%{0}%", fixedBegin));
			}
			catch (Exception ex)
			{
				return false;
			}
		}

		#endregion

		#region 文件权限

		/// <summary>
		///为文件添加users，everyone用户组的完全控制权限
		/// </summary>
		/// 文件路径
		/// <param name="filePath"></param>
		public static bool AddSecurityControllFile(string filePath)
		{
			if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
			{
				return false;
			}

			try
			{
				//获取文件信息
				FileInfo fileInfo = new FileInfo(filePath);
				//获得该文件的访问权限
				System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
				//添加ereryone用户组的访问权限规则 完全控制权限
				fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
				//添加Users用户组的访问权限规则 完全控制权限
				fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
				//设置访问权限
				fileInfo.SetAccessControl(fileSecurity);

				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

		/// <summary>
		/// 读取文件、文件夹权限
		/// </summary>
		/// <param name="path"></param>
		public static bool ReadPathRule(string path)
		{
			FileInfo fileInfo = new FileInfo(path);
			FileSecurity fs = fileInfo.GetAccessControl(AccessControlSections.All);
			foreach (FileSystemAccessRule rule in fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
			{
				if ((rule.FileSystemRights & FileSystemRights.Read) != 0)
				{
					return true;
				}
			}
			return false;
		}

		#endregion

		#region 检测文件类型

		/// <summary>
		/// 获取程序入口文件类型
		/// </summary>
		/// <param name="fileName"></param>
		/// <returns></returns>
		public static bool IsProgramExe(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				return false;
			}

			string fileSuffix = Path.GetExtension(fileName);
			if (string.IsNullOrEmpty(fileSuffix))
			{
				return false;
			}

			switch (fileSuffix)
			{
				case ".exe":
					{
						return true;
					}
				default:
					return false;
			}
		}

		/// <summary>
		/// 检测是否图片类型
		/// </summary>
		/// <param name="filePath"></param>
		/// <returns></returns>
		public static bool IsImageType(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
			{
				return false;
			}

			string fileSuffix = Path.GetExtension(filePath);
			if (string.IsNullOrEmpty(fileSuffix))
			{
				return false;
			}
			switch (fileSuffix)
			{
				case ".jpg":
				case ".jpeg":
				case ".png":
				case ".bmp":
				case ".gif":
					{
						return true;
					}
				default:
					return false;
			}
		}

		#endregion

		#region 检查路径是否合法

		/// <summary>
		/// 检查路径是否合法
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static bool HasDriveLetter(string path)
		{
			string root = Path.GetPathRoot(path);
			// 如果root非空且包含冒号，则说明是盘符路径
			return !string.IsNullOrEmpty(root) && root.Contains(":");
		}

		#endregion

		#region 拷贝文件夹下所有文件

		/// <summary>
		/// 拷贝所有文件
		/// </summary>
		/// <param name="sourceFolder"></param>
		/// <param name="destFolder"></param>
		public static void CopyFolder(string sourceFolder, string destFolder)
		{
			if (!Directory.Exists(destFolder))
			{
				Directory.CreateDirectory(destFolder);
			}

			string[] files = Directory.GetFiles(sourceFolder);
			foreach (string file in files)
			{
				string fileName = Path.GetFileName(file);
				string destFile = Path.Combine(destFolder, fileName);
				File.Copy(file, destFile, true); // true to overwrite
			}

			string[] folders = Directory.GetDirectories(sourceFolder);
			foreach (string folder in folders)
			{
				string folderName = Path.GetFileName(folder);
				string destDir = Path.Combine(destFolder, folderName);
				CopyFolder(folder, destDir); // Recursive copy
			}
		}

		/// <summary>
		/// 检查目录下是否存在文件
		/// </summary>
		/// <param name="filePath"></param>
		/// <returns></returns>
		public static bool IsExistFile(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
			{
				return false;
			}

			string[] files = Directory.GetFiles(filePath);
			if (files.Length > 0)
			{
				return true;
			}

			string[] folders = Directory.GetDirectories(filePath);
			if (folders.Length <= 0)
			{
				return false;
			}

			foreach (string folder in folders)
			{
				string folderName = Path.GetFileName(folder);
				string destDir = Path.Combine(filePath, folderName);
				IsExistFile(destDir); // Recursive check
			}

			return false;
		}

		#endregion

		#region 获取文件所在文件夹名称

		public static string GetDirectoryName(string filePath)
		{
			if (string.IsNullOrEmpty(filePath))
			{
				return string.Empty;
			}

			// 实例化DirectoryInfo（指向文件）
			DirectoryInfo fileDir = new DirectoryInfo(filePath);

			return fileDir.Parent?.Name ?? fileDir.Root.Name;
		}

		/// <summary>
		/// 获取文件名称
		/// </summary>
		/// <param name="filePath"></param>
		/// <returns></returns>
		public static string GetFileName(string filePath)
		{
			if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
			{
				return string.Empty;
			}

			string fileName = Path.GetFileNameWithoutExtension(filePath);
			if (string.IsNullOrEmpty(fileName))
			{
				return string.Empty;
			}

			if (fileName.Length == 1)
			{
				return fileName.ToUpper();
			}

			return char.ToUpper(fileName[0]) + fileName.Substring(1);
		}

		#endregion

		#region 生成图片

		/// <summary>
		/// 生成指定像素图片并落地，默认20像素
		/// </summary>
		/// <param name="sourceImagePath"></param>
		/// <param name="targetImagePath"></param>
		/// <param name="pixel"></param>
		public static void GeneratorSizeImage(string sourceImagePath, string targetImagePath, int pixel = 24)
		{
			if (!File.Exists(sourceImagePath) || string.IsNullOrEmpty(targetImagePath))
			{
				return;
			}

			if (!IsImageType(sourceImagePath))
			{
				return;
			}

			string targetDir = Path.GetDirectoryName(targetImagePath);
			if (!Directory.Exists(targetDir))
			{
				Directory.CreateDirectory(targetDir);
			}

			using (Bitmap originalImage = new Bitmap(sourceImagePath))
			{
				// 创建新的16x16像素大小的Bitmap对象
				Bitmap resizedImage = new Bitmap(pixel, pixel);
				using (Graphics g = Graphics.FromImage(resizedImage))
				{
					// 设置高质量插值法
					g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
					g.DrawImage(originalImage, 0, 0, pixel, pixel); // 从(0,0)开始绘制，大小为16x16
				}

				// 保存或显示缩小后的图片
				resizedImage.Save(targetImagePath);
			}
		}

		/// <summary>
		/// 在指定位置绘制传入名称首字母的图片，指定尺寸
		/// </summary>
		/// <param name="targetImagePath">目标图片路径</param>
		/// <param name="name">名称</param>
		/// <param name="pixel">指定像素</param>
		/// <param name="fontSize">字体大小</param>
		/// <param name="x"> 文本位置X</param>
		/// <param name="y">文本位置Y</param>
		public static void GeneratorImage(string targetImagePath, string name, int pixel = 50, float fontSize = 24, int x = 11, int y = 10)
		{
			if (string.IsNullOrEmpty(targetImagePath) || string.IsNullOrEmpty(name))
			{
				return;
			}

			string targetDir = Path.GetDirectoryName(targetImagePath);
			if (!Directory.Exists(targetDir))
			{
				Directory.CreateDirectory(targetDir);
			}

			// 创建一个新的Bitmap对象，大小为48x48像素
			using (Bitmap bitmap = new Bitmap(pixel, pixel))
			{
				// 创建一个Graphics对象用于绘图
				using (Graphics graphics = Graphics.FromImage(bitmap))
				{
					// 设置背景色
					graphics.Clear(Color.FromArgb(39, 198, 240));

					// 设置文本样式（字体，大小，颜色）
					Font font = new Font("微软雅黑", fontSize, System.Drawing.FontStyle.Bold, GraphicsUnit.Pixel);
					Brush textBrush = Brushes.Black;
					PointF point = new PointF(x, y); // 文本位置

					// 绘制文本
					graphics.DrawString(name.Length > 0 ? char.ToUpper(name[0]).ToString() : "", font, textBrush, point);
				}
				bitmap.Save(targetImagePath);
			}
		}

		#endregion
	}
}
